package com.heima.user.service.impl;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.heima.common.exception.CustomException;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.user.dtos.LoginDto;
import com.heima.model.user.pojos.ApUser;
import com.heima.user.service.ApUserLoginService;
import com.heima.user.service.ApUserService;
import com.heima.utils.common.AppJwtUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import java.util.HashMap;
import java.util.Map;

/**
 *
 */
@Service
@Slf4j
public class ApUserLoginServiceImpl implements ApUserLoginService {

    @Autowired
    ApUserService apUserService;

    @Override
    // app端登陆
    public ResponseResult login(LoginDto dto) {
        if (dto == null){
            throw new CustomException(AppHttpCodeEnum.PARAM_REQUIRE);
        }
        // 判断是正常登陆还是不登陆就看看
        if (dto.getPhone() != null){
            // 是正常登陆
            // 通过电话查询记录，如果为空抛出异常
            ApUser apUser = apUserService.getOne(Wrappers.<ApUser>lambdaQuery()
                    .eq(ApUser::getPhone, dto.getPhone()));
            if (apUser == null){
                throw new CustomException(AppHttpCodeEnum.USER_NOT_EXIST,"该app用户不存在");
            }else {
                // 判断密码是否正确
                String password = apUser.getPassword();
                String inputPwd = DigestUtils.md5DigestAsHex((dto.getPassword() + apUser.getSalt()).getBytes());
                if (!password.equals(inputPwd)){
                    // 说明密码错误，抛出异常
                    throw new CustomException(AppHttpCodeEnum.LOGIN_PASSWORD_ERROR);
                }else {
                    // 进行登陆操作
                    // 颁发凭证
                    String token = AppJwtUtil.getToken(Long.valueOf(apUser.getId()));
                    // 封装返回信息
                    Map<String, Object> map = new HashMap<>();
                    // 去除敏感信息
                    apUser.setPassword("");
                    apUser.setSalt("");
                    map.put("apUser",apUser);
                    map.put("token",token);
                    return ResponseResult.okResult(map);
                }
            }
        }else {
            // 说明按照设备id进行登陆
            // 直接颁发凭证
            String token = AppJwtUtil.getToken(0L);
            Map map = new HashMap<String,Object>();
            map.put("token",token);
            return ResponseResult.okResult(map);
        }
    }
}
